import ChatMessageStateStore from "@/store/chat-message";
import {
  queryChatMessagesByCursor,
  insertChatMessage,
  deleteChatMessage,
  updateChatMessage,
  deleteBatchMessagesByIds,
  deleteAllMessagesBySessionId,
} from "@/services/sqlite/chat-message";
import CurrentUserIdManager from "@/utils/user-utils";
import { ChatMessageCreate, ChatMessageUpdate } from "@/types/chat-message";
import {
  useChatDetailPageActions,
  useChatDetailPageState,
} from "@/hooks/chat/chat-detail-page";
import { ChatSession } from "@/types/chat-session";

export const useChatMessageState = () => {
  const chatDetailPageState = useChatDetailPageState();
  const chatMessageState = ChatMessageStateStore((state) => state.state);
  return {
    ...chatMessageState,
    ...chatDetailPageState,
  };
};

export const useChatMessageActions = () => {
  const actions = ChatMessageStateStore((state) => state.actions);
  const chatDetailPageActions = useChatDetailPageActions();
  const state = ChatMessageStateStore((state) => state.state);
  const ownerId = CurrentUserIdManager.getUserId();

  async function getMessages(sessionId: string) {
    try {
      actions.setLoading(true);
      // 获取到目前的state时间戳最旧的一条消息，然后往后搜索
      const hasMessages = state.messages.length > 0;
      const lastTime = hasMessages
        ? state.messages[0].createTime
        : null;
      const chatMessages = await queryChatMessagesByCursor({
        sessionId,
        ownerId,
        lastTime,
      });
      if (hasMessages) {
        actions.addBatchMessages(chatMessages);
      } else {
        actions.setMessages(chatMessages.reverse());
      }
    } catch (error) {
      console.error("获取消息列表失败:", error);
    } finally {
      actions.setLoading(false);
    }
  }

  async function addMessage(
    message: Omit<ChatMessageCreate<any, any>, "ownerId">
  ) {
    try {
      actions.addMessage(message);
      await insertChatMessage({ ...message, ownerId });
    } catch (error) {
      console.error("添加消息失败:", error);
    }
  }

  function clearMessages() {
    actions.setMessages([]);
  }

  async function deleteMessage(messageId: string) {
    try {
      actions.deleteMessage(messageId);
      await deleteChatMessage({ messageId, ownerId });
    } catch (error) {
      console.error("删除消息失败:", error);
    }
  }

  async function clearAllMessages() {
    actions.setMessages([]);
  }

  async function deleteBatchMessages(messageIds: string[]) {
    try {
      actions.deleteBatchMessages(messageIds);
      await deleteBatchMessagesByIds(messageIds, ownerId);
    } catch (error) {
      console.error("批量删除消息失败:", error);
    }
  }

  async function deleteAllMessages(sessionId: string) {
    try {
      actions.setMessages([]);
      // 这里可以调用删除所有消息的服务方法
      await deleteAllMessagesBySessionId({ sessionId, ownerId });
    } catch (error) {
      console.error("删除所有消息失败:", error);
    }
  }

  async function updateMessage(
    messageUpdate: Omit<ChatMessageUpdate, "ownerId">
  ) {
    try {
      actions.updateMessage({ ...messageUpdate, ownerId });
      await updateChatMessage({ ...messageUpdate, ownerId });
    } catch (error) {
      console.error("更新消息失败:", error);
    }
  }

  // 设置当前聊天详情页的会话
  function setCurrentChatDetailState(session: ChatSession) {
    chatDetailPageActions.setCurrentChatDetailState(session);
  }

  return {
    getMessages,
    addMessage,
    clearMessages,
    deleteMessage,
    clearAllMessages,
    deleteBatchMessages,
    deleteAllMessages,
    updateMessage,
    setCurrentChatDetailState,
    ...chatDetailPageActions,
  };
};
